<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <template #email="{ record }">
        <span :class="prefixCls + '-verify-target'">{{ record.email }}</span>
        <a-tooltip placement="topLeft" v-if="!record.emailStatus || record.emailStatus === VerifyStatus.NO_VERIFY">
          <template #title>
            <span>
              邮箱未验证，不能接收消息。
              <a @click="handleEmailVerify(record)">发送验证</a>
            </span>
          </template>
          <ExclamationCircleTwoTone two-tone-color="#FAAD14"/>
        </a-tooltip>
      </template>

      <template #phone="{ record }">
        <span :class="prefixCls + '-verify-target'">{{ record.phone }}</span>
        <a-tooltip placement="topLeft" v-if="!record.phoneStatus || record.phoneStatus === VerifyStatus.NO_VERIFY">
          <template #title>
            <span>
              手机未验证，不能接收消息。
              <a @click="handlePhoneVerify(record)">发送验证</a>
            </span>
          </template>
          <ExclamationCircleTwoTone two-tone-color="#FAAD14"/>
        </a-tooltip>
      </template>
      
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
    </BasicTable>
    <ReceiverSubscribeTable @register="registerSubscribeListDrawer" />
    <ReceiverDrawer @register="registerDrawer" @success="reload" showFooter />
    <ReceiverDesc @register="registerDesc"></ReceiverDesc>
    <VerifyModal @register="registerVerifyModal" :submitCallback="handleSubmitVerify"/>
  </div>
</template>
<script lang="ts" name="msg-receiver-list" setup>
import { ref } from 'vue'
import { ExclamationCircleTwoTone } from '@ant-design/icons-vue';
import Icon from '/@/components/Icon/src/Icon.vue';
import { BasicTable, TableAction } from '/@/components/Table';
import { useDrawer } from '/@/components/Drawer';
import { useModal } from '/@/components/Modal';
import ReceiverDrawer from './components/ReceiverDrawer.vue';
import ReceiverDesc from './components/ReceiverDesc.vue';
import { BizType } from '/@/api/sys/model/msgPushModel';
import ReceiverSubscribeTable from './components/ReceiverSubscribeTable.vue';
import { columns, searchFormSchema, VerifyStatus } from './receiver.data';
import { pageReceiver, deleteRole, batchDeleteRole, sendCaptcha, checkCaptcha } from './receiver.api';
import { useListPage } from '/@/hooks/system/useListPage'
import { VerifyModal }  from '/@/components/BizVerify';
import { useAttrs } from '/@/hooks/core/useAttrs';
const attrs = useAttrs({ excludeDefaultKeys: false });

const [registerSubscribeListDrawer, { openDrawer: openSubscribeListDrawer }] = useDrawer();
const [registerDrawer, { openDrawer }] = useDrawer();
const [registerDesc, { openDrawer: openReceiverDesc }] = useDrawer();
const [registerVerifyModal, { openModal: openVerifyModal }] = useModal();
const currentRecord = ref<any>({})

const { prefixCls, tableContext } = useListPage({
  designScope: 'msg-receiver',
  tableProps: {
    title: '接收人列表',
    api: pageReceiver,
    columns: columns,
    bordered: false,
    formConfig: {
      schemas: searchFormSchema
    },
    actionColumn: {
      width: 180,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
    rowSelection: null
  }
})
const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

/**
 * 新增
 */
function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
  });
}
/**
 * 编辑
 */
function handleEdit(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
  });
}
/**
 * 详情
 */
function handleDetail(record) {
  openReceiverDesc(true, {
    record,
    isUpdate: true,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteRole({ id: record.id }, reload);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDeleteRole({ ids: selectedRowKeys.value }, reload);
}


/**
 * 订阅的消息任务
 */
function handleOpenSubscribeList(record) {
  openSubscribeListDrawer(true, { record })
}
/**
 * 操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '订阅管理',
      onClick: handleOpenSubscribeList.bind(null, record),
    },
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    }
  ]
}

/**
 * 下拉操作栏
 */
function getDropDownAction(record) {
  let resp: any = [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    },
  ]
  if (record.roleCode !== "default") {
    resp.push({
      label: '删除',
      popConfirm: {
        title: `是否确认删除 ${record.roleName}`,
        confirm: handleDelete.bind(null, record),
      },
    })
  }

  return resp
}

const handleEmailVerify = (record) => {
  currentRecord.value = record
  openVerifyModal(true, {
    verifyType: 'verifyEmail',
    toUser: record.email,
    bizType: BizType.MSG_RECEIVER,
    apiParams: {receiverId: record.id},
    api: sendCaptcha
  });
  
}

const handlePhoneVerify = (record) => {
  currentRecord.value = record
  openVerifyModal(true, {
    verifyType: 'verifyPhone',
    toUser: record.phone,
    apiParams: {receiverId: record.id},
    api: sendCaptcha
  });
}

const handleSubmitVerify = async (data) => {
  console.log('submitVerify: ', data);
  await checkCaptcha(data)
  reload()
}

</script>

<style lang="less">
  @prefix-cls: ~'@{namespace}-msg-receiver';

  .@{prefix-cls}-verify-target {
    margin-right: 2px;
    margin-left: 2px;
  }
</style>
